package com.db.logger.appender;

import com.db.logger.service.ConfigService;

import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

public class AppenderFactory {
    private static Map<String, Appender> appenderMap = new HashMap<>();

    public synchronized static Appender getAppender(String appenderName, String loggerName) {
        if (appenderMap.containsKey(appenderName)) {
            return appenderMap.get(appenderName);
        } else {
            Appender appender = null;
            String appenderType = ConfigService.getProperty(appenderName, "type");
            if (appenderType == null) {
                throw new RuntimeException("Can not get appender type for " + appenderName + " for " + loggerName);
            }
            switch (appenderType) {
                case "file":
                    try {
                        appender = new FileAppender(ConfigService.getProperty(appenderName, "file"));
                    } catch (FileNotFoundException e) {
                        throw new RuntimeException("Can not init file appender for " + appenderName + " for " + loggerName);
                    }
                    break;
                case "console":
                    appender = new ConsoleAppender();
                    break;
            }
            if (appender != null) {
                appenderMap.put(appenderName, appender);
                return appender;
            } else {
                throw new RuntimeException("Can not init appender for " + appenderName + " for " + loggerName);
            }
        }
    }
}
